package com.bdy.lm.taximanager.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bdy.lm.taximanager.R;
import com.bdy.lm.taximanager.app.MyApp;
import com.bdy.lm.taximanager.http.HttpJson;
import com.bdy.lm.taximanager.model.DriverInfo;
import com.bdy.lm.taximanager.model.MessagePackaging;
import com.bdy.lm.taximanager.rfid.RFIDCallback;
import com.bdy.lm.taximanager.rfid.TotalManager;
import com.bdy.lm.taximanager.util.AutoStartReceiver;
import com.bdy.lm.taximanager.util.FileUtils;
import com.bdy.lm.taximanager.util.JsonUtils;
import com.bdy.lm.taximanager.util.TimeUtils;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;


public class LoginActivity extends Activity implements RFIDCallback {

    private boolean check = true;
    private DriverInfo driverInfo;
    private SharedPreferences.Editor editor;
    private Handler handler;
    private HttpJson httpJson = new HttpJson();
    private String id = "195996CE";//= null;//
    private boolean isLoginSuccess = false;
    private JSONObject jsonObject;
    private TextView loginSuccess;
    private MessagePackaging messagePackaging = new MessagePackaging(101);
    private SharedPreferences sharedPreferences;
    private int times = 8;
    private Logger logger;

    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        //请求窗口的标题 为无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //要求窗口全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);

        loginSuccess = (TextView) findViewById(R.id.login_success);
        driverInfo = DriverInfo.getDriverInfo();

        //启动RFID监听
        TotalManager.instance().setRFIDCallback(this);
        System.out.println("开机时间" + AutoStartReceiver.getUpTimeString(this));

        logger = Logger.getLogger(this.getClass());

        System.out.println("isLoginSuccess" + isLoginSuccess);

        //检测是否有刷卡
        new Thread(new Runnable() {
            public void run() {
                while(!isLoginSuccess) {
                    if(check) {
                        delay(100);
                        if (id != null) {//如果有则启动登录线程
                            handler.sendEmptyMessage(501);
                            check = false;//停止检测刷卡信息
                            System.out.println("刷卡");
                        }
                    } else {
                        delay(500);
                    }
                }
            }
        }).start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 501) {//启动登录线程
                    sharedPreferences = getSharedPreferences(id, Context.MODE_PRIVATE);
                    login();
                } else if (msg.what == 502) {
                    loginSuccess.setText("用户不存在，请联系管理员！");
                } else if (msg.what == 503) {
                    loginSuccess.setText("登录成功！");
                    MyApp.threadRun = true;
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    System.out.println("LoginActivity已销毁");
                    finish();
                } else if (msg.what == 504) {
                    loginSuccess.setText("登陆失败，请检查网络连接并重新刷卡！");
                }
            }
        };
    }

    @Override
    public void processCardID(String paramString) {
        this.id = paramString;
        Log.d("thisID", paramString);
    }

    private void login() {
        final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppTheme_Dark_Dialo);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("已识别，正在登录中...");
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);

        final JSONObject loginMsg = JsonUtils.mapToJsonObject(messagePackaging.getLoginMessageMap(id));
        Log.d("loginMsg", loginMsg.toString());

        new Thread(new Runnable() {
            @Override
            public void run() {
                //首先检测本地是否有用户信息，有就直接读取
                System.out.println("登录检查本地信息" + sharedPreferences.contains(id));
                if (sharedPreferences.contains(id)) {
                    System.out.println("登陆 本地已有信息");
                    driverInfo.setDriverName(sharedPreferences.getString(id, null));
                    driverInfo.setICID(id);
                    driverInfo.setDriverCompany(sharedPreferences.getString("driverCompany", null));
                    driverInfo.setAreaId(sharedPreferences.getString("areaId", null));
                    driverInfo.setDriverPhoto(FileUtils.getDiskBitmap(FileUtils.getDriverPhotoDir() + id + ".jpg"));
                    if (sharedPreferences.getString("inTime", null) == null) {
                        editor = sharedPreferences.edit();
                        editor.putString("inTime", TimeUtils.getFormatTime());
                        editor.commit();
                        driverInfo.setInTime(TimeUtils.getInOutTime());
                    }
                    handler.sendEmptyMessage(503);//显示登陆成功，并且跳转
                    isLoginSuccess = true;//通知检测刷卡的线程结束
                    MyApp.threadRun = true;//启动后台线程
                    progressDialog.dismiss();
                    httpJson.HttpJsonPost(loginMsg, MyApp.serverUrl);//利用本地信息登陆成功之后通知服务器
                } else {
                    System.out.println("登录请求信息：" + loginMsg.toString());
                    logger.info("登录请求信息：" + loginMsg.toString());
                    //若本地没有用户信息，则开始向服务器查询
                    while (times >= 0) {//每隔2秒发送一次请求，共发送8次，超时则报错
                        httpJson.HttpJsonPost(loginMsg, MyApp.serverUrl);
                        System.out.println("登录时：" + httpJson.getPostJson());
                        logger.info("登录时：" + httpJson.getPostJson());
                        delay(2000);
                        times = times - 1;
                        if (httpJson.getPostJson() != null) {
                            jsonObject = httpJson.getPostJson();
                            times = -1;
                        }
                        System.out.println("登录times倒计时：" + times);
                        logger.info("登录times倒计时：" + times);
                    }
                    //十次结束以后若jsonObject还为空，则报错，后面内容不再执行
                    if (jsonObject == null) {
                        handler.sendEmptyMessage(504);
                        check = true;//启动检测刷卡线程
                        id = null;
                        times = 8;
                        progressDialog.dismiss();
                    } else {//若已成功获取服务器返回信息，则启动验证过程
                        try {
                            System.out.println("登录结果：" + jsonObject.toString());
                            if (jsonObject.getString("ICID").equals(id)) {
                                driverInfo.setDriverName(jsonObject.getString("driverName"));
                                driverInfo.setICID(id);
                                driverInfo.setDriverCompany(jsonObject.getString("driverCompany"));
                                driverInfo.setAreaId(jsonObject.getString("areaId"));
                                driverInfo.setInTime(TimeUtils.getInOutTime());
                                editor = sharedPreferences.edit();
                                editor.putString(id, driverInfo.getDriverName());
                                editor.putString("driverCompany", driverInfo.getDriverCompany());
                                editor.putString("areaId", driverInfo.getAreaId());
                                editor.putString("inTime", TimeUtils.getFormatTime());
                                editor.commit();
                                handler.sendEmptyMessage(503);
                                isLoginSuccess = true;
                                MyApp.threadRun = true;//启动后台线程
                                progressDialog.dismiss();
                            } else {
                                handler.sendEmptyMessage(502);
                                check = true;
                                id = null;
                                times = 8;
                                progressDialog.dismiss();
                            }
                        } catch (JSONException e) {
                            logger.error(e);
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    private void delay(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            logger.error(e);
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //isSuccess = true;
    }


//                    if (id.equals("19 58 DD CE")) {
//                    driverInfo.setDriverName("张三");
//                    driverInfo.setICID(id);
//                    driverInfo.setDriverCompany("福州**出租车公司");
//                    driverInfo.setInTime(TimeUtils.getFormatTime());
//                    if (FileUtils.isFileExist("/storage/sdcard1/出租车服务管理系统/" + id + ".jpg")) {
//                        driverInfo.setDriverPhoto(FileUtils.getDiskBitmap("/storage/sdcard1/出租车服务管理系统/" + id + ".jpg"));
//                    }
//                    editor = sharedPreferences.edit();
//                    editor.putString(id, driverInfo.getDriverName());
//                    editor.putString(id + "driverCompany", driverInfo.getDriverCompany());
//                    editor.putString(id + "inTime", TimeUtils.getFormatTime());
//                    editor.commit();
//                    handler.sendEmptyMessage(520);
//                    isSuccess = true;
//                    //httpJson.HttpJsonPost();//利用本地信息登陆成功后发送
//                    progressDialog.dismiss();
//                } else {
//                    id = null;
//                    check = true;
//                    handler.sendEmptyMessage(502);
//                    progressDialog.dismiss();
//                }

    //httpJson.HttpStringPost("http://172.16.69.59:8080/TaxiManagerServer/ProcessHeartBit");
    //System.out.println("收到：");
    //httpJson.HttpJsonGet("http://172.16.69.59:8080/TaxiManagerServer/ProcessHeartBit");
    //delay(1000);
    //httpJson.HttpStringGet("http://172.16.69.59:8080/LiMing/servlet/AndroidServlet");
    //httpJson.HttpJsonPost(turnToJson.mapToJsonObject(messagePackaging.getLoginMessageMap(id)), "http://172.16.69.59:8080/TaxiManagerServer/ProcessHeartBit");
//                        httpJson.HttpJsonPost(turnToJson.mapToJsonObject(messagePackaging.getLoginMessageMap(id)), "http://172.16.69.59:8080/LiMing/servlet/AndroidServlet");
    //System.out.println("3收到：" + httpJson.getPostJson());
}
